package com.of.service;

import com.of.vo.ImageVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileServiceImp implements FileService {

    private String rootDir = "D:\\a\\images";

    private String rootUrl ="http://image.of.com"; //定义


    @Override
    public ImageVo upload(MultipartFile file) {
        //1.获取图片名称,全部转化为小写
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif)$")) {
            return null;
        }
        //2.通过校验宽度和高度判断是否为图片 bufferedImage图片包装对象
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0) {
                return null;
            }
            //3.实现分目录的存储
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDir = rootDir + datePath;
            File dirFile = new File(fileDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //4.动态生成UUID
            String UUID = java.util.UUID.randomUUID().toString();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            fileName = UUID + fileType;
            //5.实现文件上传
            String path=fileDir+fileName;
            file.transferTo(new File(path));
            //6.准备ImageVo数据返回，/2021.11.11/uuid.jpg
            //封装vo对象
            String virtualPath=datePath+fileName;
            //String urlPath="https://img12.360buyimg.com/babel/s320x320_jfs/t1/190949/34/13442/115712/60f0eaa2E213b8362/42bbdf2748661a26.jpg!cc_320x320.webp";
             String urlPath=rootUrl+virtualPath;
            System.out.println(urlPath);
            ImageVo imageVo=new ImageVo(virtualPath,urlPath,fileName);
            return imageVo;
        } catch (IOException e) {
            //一般条件下为了不影响代码结构,将检查异常,转化为运行时异常
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //删除文件，，需要文件的全路径
    @Override
    @Transactional
    public void deleteFile(String virtualPath) {
        String localPath=rootDir+virtualPath;//根路径+虚拟路径
        File file=new File(localPath);
        if (file.exists()){//如果文件存在，删除文件
            file.delete();
        }

    }
}
